package com.sdx.console.crmquestion.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.crm.entity.CrmQuestionType;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.crmquestion.entity.*;
import com.sdx.console.crmquestion.service.*;
import com.sdx.console.crmquestion.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * 客服常见问题 接口
 */
@RequestMapping("/crm/crmQuestion")
@Controller
public class CrmQuestionController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(CrmQuestionController.class);
    private static final String MODEL = "/crm/crmQuestion";

    @Resource
	private CrmQuestionService crmQuestionService;

    @Resource
    private ResCloudFileService resCloudFileService;

    @Resource
    private SQLManager sqlManager;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        CrmQuestionType questionType = new CrmQuestionType();
        questionType.setTenantId(user.getTenantId());
        view.addObject("types", sqlManager.template(questionType));
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("crm.crmQuestion.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("crm.crmQuestion.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer id) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        CrmQuestion crmQuestion = crmQuestionService.queryById(id);
        view.addObject("crmQuestion", crmQuestion);
		setPageParam(view,request);
		try {
			view.addObject("crmQuestionJson", JacksonUtils.toJsonString(crmQuestion,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("crm.crmQuestion.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        view.addObject("crmQuestion", new CrmQuestion());
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("crm.crmQuestion.query")
    @ResponseBody
    public JsonResult<PageQuery> list(CrmQuestion condtion,HttpServletRequest request)
    {
        CoreUser user = getLoginUser(request);
        condtion.setTenantId(user.getTenantId());
        PageQuery page = condtion.getPageQuery();
        crmQuestionService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,CrmQuestion crmQuestion,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			crmQuestion.setCreatedBy(user.getId().intValue());
            crmQuestion.setTenantId(user.getTenantId());
			crmQuestion.setCreatedName(user.getName());
			crmQuestion.setCreatedTime(new Date());
			crmQuestion.setUpdatedBy(user.getId().intValue());
			crmQuestion.setUpdatedName(user.getName());
			crmQuestion.setUpdatedTime(new Date());
			crmQuestionService.save(crmQuestion);
		} else {
			crmQuestion.setUpdatedBy(user.getId().intValue());
			crmQuestion.setUpdatedName(user.getName());
			crmQuestion.setUpdatedTime(new Date());
			crmQuestionService.updateTemplate(crmQuestion);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("crm.crmQuestion.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)CrmQuestion crmQuestion,HttpServletRequest request
		)
    {

        return save(true,crmQuestion,request
		);
    }

    @PostMapping("/update.json")
    @Function("crm.crmQuestion.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  CrmQuestion crmQuestion,HttpServletRequest request
		) {
		return save(false,crmQuestion,request
		);
    }



    @GetMapping("/view.json")
    @Function("crm.crmQuestion.query")
    @ResponseBody
    public JsonResult<CrmQuestion>queryInfo(Integer id) {
        CrmQuestion crmQuestion = crmQuestionService.queryById( id);
        return  JsonResult.success(crmQuestion);
    }

    @PostMapping("/delete.json")
    @Function("crm.crmQuestion.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        crmQuestionService.batchDelCrmQuestion(idList);
        return JsonResult.success();
    }

    @RequestMapping("/upload.json")
    @ResponseBody
    public JSONObject uploadImg(MultipartFile file) {
        JSONObject jsobject = new JSONObject();
        String dir = DateUtil.now("yyyyMMdd");
        String subPath = "/images/crmquestion/"+dir+"/";
        String bucketName = "sdxcomm";
        if (!FileUtils.isEmptyFile(file)) {
            try
            {
                String fileNamePair = FileUtils.upload(subPath,file);
                String storeFile = fileNamePair.split("::")[0];
                storeFile = subPath+storeFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+storeFile,bucketName,storeFile.substring(1));
                String url = "https://sdxcomm."+ ConfigService.ossDomain+storeFile;
                jsobject.put("url",url);
                jsobject.put("state", "SUCCESS");
                jsobject.put("title", "");
                jsobject.put("original", "");
                resCloudFileService.insertResFile(ResCloudFile.ALI,storeFile,url,"a","客服问题回答");
            }catch(Exception e) {
                e.printStackTrace();
                jsobject.put("state", "FAIL");
                jsobject.put("title", "");
                jsobject.put("original", "");
                jsobject.put("url","");
            }
        }
        return jsobject;
    }


    /**
     * 返回 ueditor 图片上传的配置参数
     * @return
     */
    @RequestMapping("/config")
    @ResponseBody
    public String config(){
        String UEDITOR_CONFIG = "{\n" +
                "    \"imageActionName\": \"uploadimage\",\n" +
                "    \"imageFieldName\": \"file\",\n" +
                "    \"imageMaxSize\": 2048000,\n" +
                "    \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "    \"imageCompressEnable\": true,\n" +
                "    \"imageCompressBorder\": 1600,\n" +
                "    \"imageInsertAlign\": \"none\",\n" +
                "    \"imageUrlPrefix\": \"\",\n" +
                "    \"imagePathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "\n" +
                "    \"scrawlActionName\": \"uploadscrawl\",\n" +
                "    \"scrawlFieldName\": \"file\",\n" +
                "    \"scrawlPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"scrawlMaxSize\": 2048000,\n" +
                "    \"scrawlUrlPrefix\": \"\",\n" +
                "    \"scrawlInsertAlign\": \"none\",\n" +
                "\n" +
                "    \"snapscreenActionName\": \"uploadimage\",\n" +
                "    \"snapscreenPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"snapscreenUrlPrefix\": \"\",\n" +
                "    \"snapscreenInsertAlign\": \"none\",\n" +
                "\n" +
                "    \"catcherLocalDomain\": [\"127.0.0.1\", \"localhost\", \"img.baidu.com\"],\n" +
                "    \"catcherActionName\": \"catchimage\",\n" +
                "    \"catcherFieldName\": \"source\",\n" +
                "    \"catcherPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"catcherUrlPrefix\": \"\",\n" +
                "    \"catcherMaxSize\": 2048000,\n" +
                "    \"catcherAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "\n" +
                "    \"videoActionName\": \"uploadvideo\",\n" +
                "    \"videoFieldName\": \"upfile\",\n" +
                "    \"videoPathFormat\": \"/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"videoUrlPrefix\": \"\",\n" +
                "    \"videoMaxSize\": 102400000,\n" +
                "    \"videoAllowFiles\": [\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\"],\n" +
                "\n" +
                "    \"fileActionName\": \"uploadfile\",\n" +
                "    \"fileFieldName\": \"upfile\",\n" +
                "    \"filePathFormat\": \"/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"fileUrlPrefix\": \"\",\n" +
                "    \"fileMaxSize\": 51200000,\n" +
                "    \"fileAllowFiles\": [\n" +
                "        \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
                "        \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
                "        \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
                "    ],\n" +
                "\n" +
                "    \"imageManagerActionName\": \"listimage\",\n" +
                "    \"imageManagerListPath\": \"/ueditor/jsp/upload/image/\",\n" +
                "    \"imageManagerListSize\": 20,\n" +
                "    \"imageManagerUrlPrefix\": \"\",\n" +
                "    \"imageManagerInsertAlign\": \"none\",\n" +
                "    \"imageManagerAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "\n" +
                "    \"fileManagerActionName\": \"listfile\",\n" +
                "    \"fileManagerListPath\": \"/ueditor/jsp/upload/file/\",\n" +
                "    \"fileManagerUrlPrefix\": \"\",\n" +
                "    \"fileManagerListSize\": 20,\n" +
                "    \"fileManagerAllowFiles\": [\n" +
                "        \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
                "        \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
                "        \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
                "    ] \n" +
                "\n" +
                "}";
        return UEDITOR_CONFIG;
    }

    @RequestMapping("/getTypes.json")
    @ResponseBody
    public List<CrmQuestionType>  getBatch(Integer come) {
        CrmQuestionType questionType = new CrmQuestionType();
        questionType.setCome(come);
        List<CrmQuestionType> list = sqlManager.template(questionType);
        return  list;
    }



}
